<?php
/** 
 * @brief 数据库连接类 
 */
class Db {
    const INT_TYPE    = 0;
    const BIGINT_TYPE = 1;
    const FLOAT_TYPE  = 2;

    const FETCH_ASSOC = 'ASSOC';
    const FETCH_NUM   = 'NUM';
    const FETCH_OBJ   = 'OBJ';

    /**
     * 构造函数 
     * 
     * @note 私有函数(不能使用关键字new生成Db实例)
     * 
     * @return void
     */
	private function __construct() {
	}
	
    /**
     * 取得数据库驱动对象
     * 
     * @note 工厂模式
     * @param string $adapter 数据库驱动类型
     * @param Config $dsn 数据库DSN配置
     * 
     * @return object
     */
	public static function factory($adapter, $dsn) {
        if (is_object($dsn)) {
			$dsn = $dsn->toArray();
		}

		if (!is_array($dsn)) {
			throw new Exception('Adapter parameters must be in an array or a Config object');
		}
		
		if (!is_string($adapter) || empty($adapter)) {
			$adapter = 'mysqli';
		}
		
        $adapterName = strtolower('Db_Adapter_' . $adapter);
        $adapterName = str_replace(' ', '_', ucwords(str_replace('_', ' ', $adapterName)));
		$dbAdapter = call_user_func(array($adapterName, 'connect'), $dsn);
		return $dbAdapter;
	}

    /**
     * 获取指定的数据库驱动对象
     * 
     * @param string $dsnName 数据库DSN配置名称
     * 
     * @return object
     */
	public static function connect($dsnName = 'master') {
        $config = Yaf_Registry::get('Config');
        return self::factory($config->database->adapter, $config->database->$dsnName);
	}
}
